#include <stdio.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <sys/msg.h>
#include <pthread.h>
#include "pub_define.h"
#include "shmem.h"
#include "msg_queue_peer.h"
#include "list.h"
#include "cJSON.h"

// 设备类型定义
#define DEV_TYPE_MODBUS 1
#define DEV_TYPE_STM32  0

// 修改后的数据类型定义（匹配JSON配置）
#define DATA_TYPE_BOOL 1   // type=1
#define DATA_TYPE_INT 2    // type=2
#define DATA_TYPE_FLOAT 3  // type=3

// 共享内存结构定义
typedef union {
    int b_val;     // bool类型存储空间
    int i_val;     // 整形值存储空间
    float f_val;   // 浮点值存储空间
} val_t;

typedef struct std_node {
    int key;
    int type;            // 数据类型 (1=bool, 2=int, 3=float)
    int dev_type;        // 设备类型 (0=STM32, 1=Modbus)
    val_t old_val;
    val_t new_val;
    int ret;
} std_node_t;

// 控制消息结构
typedef struct ctl_node {
    long type;
    int key;
    char val[20];
} control_node_t;

// STM32设备配置
typedef struct {
    int key;
    char name[32];
    int type;            // 数据类型 (1=bool, 2=int, 3=float)
    int json_type;       // JSON中的原始类型 (1=bool, 2=int, 3=float)
    int index;           // 设备在STM32区域中的索引 (0-3)
} stm32_device_t;

// 全局变量
stm32_device_t *stm32_devices = NULL;
int stm32_device_count = 0;
pthread_mutex_t shm_mutex = PTHREAD_MUTEX_INITIALIZER;

// 共享内存布局
#define SHM_TOTAL_DEVICES 8
#define STM32_DEVICE_COUNT 4

// 共享内存指针
static int *shm_total_devices = NULL;
static std_node_t *shm_arr = NULL;

// 修改后的类型映射函数
int map_json_type(int json_type) {
    // 直接使用相同类型值，无需转换
    return json_type;
}

// 修改后的共享内存设备初始化
void init_shm_device(std_node_t *device, int key, int type, int dev_type) {
    device->key = key;
    device->type = type;  // 使用新的类型值
    device->dev_type = dev_type;
    device->old_val.b_val = 0;
    device->new_val.b_val = 0;
    device->ret = -1;  // 初始化为错误状态
}

// 修改后的JSON配置文件解析
int parse_config(const char *config_path) {
    FILE *fp = fopen(config_path, "r");
    if (!fp) {
        perror("fopen error");
        return -1;
    }
    
    char buf[4096] = {0};
    size_t read_size = fread(buf, 1, 4095, fp);
    fclose(fp);
    
    if (read_size == 0) {
        perror("fread error");
        return -1;
    }
    
    cJSON *root = cJSON_Parse(buf);
    if (!root) {
        printf("JSON解析错误: %s\n", cJSON_GetErrorPtr());
        return -1;
    }
    
    // 解析STM32设备
    cJSON *stm32_obj = cJSON_GetObjectItem(root, "stm32");
    if (!stm32_obj) {
        printf("未找到stm32节点\n");
        cJSON_Delete(root);
        return -1;
    }
    
    cJSON *data_array = cJSON_GetObjectItem(stm32_obj, "data");
    if (!data_array) {
        printf("未找到data数组\n");
        cJSON_Delete(root);
        return -1;
    }
    
    stm32_device_count = cJSON_GetArraySize(data_array);
    if (stm32_device_count <= 0) {
        printf("未找到STM32设备配置\n");
        cJSON_Delete(root);
        return -1;
    }
    
    if (stm32_device_count > STM32_DEVICE_COUNT) {
        printf("警告: STM32设备数超过配置限制 (%d > %d)\n", 
               stm32_device_count, STM32_DEVICE_COUNT);
    }
    
    stm32_devices = malloc(STM32_DEVICE_COUNT * sizeof(stm32_device_t));
    if (!stm32_devices) {
        perror("内存分配失败");
        cJSON_Delete(root);
        return -1;
    }
    
    // 清空设备结构
    memset(stm32_devices, 0, STM32_DEVICE_COUNT * sizeof(stm32_device_t));
    
    for (int i = 0; i < stm32_device_count; i++) {
        if (i >= stm32_device_count) break;
        
        cJSON *item = cJSON_GetArrayItem(data_array, i);
        if (!item) continue;
        
        cJSON *key_obj = cJSON_GetObjectItem(item, "key");
        cJSON *name_obj = cJSON_GetObjectItem(item, "name");
        cJSON *type_obj = cJSON_GetObjectItem(item, "type");
        
        if (!key_obj || !name_obj || !type_obj) {
            printf("设备配置缺少必要字段，跳过\n");
            continue;
        }
        
        stm32_devices[i].key = key_obj->valueint;
        stm32_devices[i].json_type = type_obj->valueint;
        stm32_devices[i].type = map_json_type(type_obj->valueint);
        stm32_devices[i].index = i;
        
        if (name_obj->valuestring) {
            strncpy(stm32_devices[i].name, name_obj->valuestring, 
                    sizeof(stm32_devices[i].name) - 1);
            stm32_devices[i].name[sizeof(stm32_devices[i].name) - 1] = '\0';
        } else {
            snprintf(stm32_devices[i].name, sizeof(stm32_devices[i].name), 
                     "STM32设备_%d", i);
        }
        
        printf("配置STM32设备: %s, key=%d, JSON类型=%d, 内部类型=%d\n", 
               stm32_devices[i].name, stm32_devices[i].key, 
               stm32_devices[i].json_type, stm32_devices[i].type);
    }
    
    cJSON_Delete(root);
    return 0;
}

// 修改后的共享内存初始化
int init_shared_memory() {
    struct shm_param para;
    size_t shm_size = sizeof(int) + SHM_TOTAL_DEVICES * sizeof(std_node_t);
    
    // 尝试初始化共享内存
    if (shm_init(&para, "shm", shm_size) != 0) {
        printf("共享内存初始化失败，尝试重新连接\n");
        
        // 尝试直接连接现有共享内存
        key_t key = ftok("/tmp/ipc/shmem/shm", 'j'); // 使用与驱动相同的MAGIC_ID
        if (key == -1) {
            perror("ftok失败");
            return -1;
        }
        
        int shmid = shmget(key, shm_size, 0666);
        if (shmid == -1) {
            perror("shmget失败");
            return -1;
        }
        
        para.id = shmid;
        para.size = shm_size;
        strcpy(para.name, "shm");
    }
    
    // 获取共享内存地址
    shm_total_devices = (int *)shm_getaddr(&para);
    if (shm_total_devices == NULL) {
        printf("获取共享内存地址失败\n");
        return -1;
    }
    
    // 设置共享内存布局
    shm_arr = (std_node_t *)(shm_total_devices + 1);
    
    // 如果设备总数为0，则设置为8
    if (*shm_total_devices == 0) {
        *shm_total_devices = SHM_TOTAL_DEVICES;
        printf("设置设备总数: %d\n", SHM_TOTAL_DEVICES);
    }
    
    // 初始化STM32设备区域
    for (int i = 0; i < stm32_device_count && i < STM32_DEVICE_COUNT; i++) {
        init_shm_device(&shm_arr[i], 
                      stm32_devices[i].key, 
                      stm32_devices[i].type,
                      DEV_TYPE_STM32);
        printf("初始化共享内存STM32设备[%d]: key=%d, type=%d\n", 
               i, stm32_devices[i].key, stm32_devices[i].type);
    }
    
    return 0;
}

// 修改后的控制线程函数
void *handler_thread(void *arg) {
    control_node_t control;
    while (1) {
        // 从消息队列接收控制信息
        if (msg_queue_recv("control", &control, sizeof(control_node_t), 0, 0) < 0) {
            perror("msg_queue_recv error");
            sleep(1);
            continue;
        }
        
        // 遍历设备列表，查找匹配的设备
        int found = 0;
        for (int i = 0; i < stm32_device_count; i++) {
            if (i >= STM32_DEVICE_COUNT) break;
            
            if (stm32_devices[i].key == control.key) {
                printf("控制STM32设备: key=%d, value=%s\n", control.key, control.val);
                
                // 根据设备类型执行不同的控制操作
                switch (stm32_devices[i].type) {
                    case DATA_TYPE_BOOL: // BOOL设备
                        // 例如：控制LED开关
                        printf("控制BOOL设备: %s\n", stm32_devices[i].name);
                        break;
                        
                    case DATA_TYPE_INT: // INT设备
                        // 例如：设置阈值
                        printf("设置INT设备: %s, 值=%s\n", 
                               stm32_devices[i].name, control.val);
                        break;
                        
                    case DATA_TYPE_FLOAT: // FLOAT设备
                        // 例如：设置浮点参数
                        printf("设置FLOAT设备: %s, 值=%s\n", 
                               stm32_devices[i].name, control.val);
                        break;
                }
                
                found = 1;
                break;
            }
        }
        
        if (!found) {
            printf("未找到key=%d的STM32设备\n", control.key);
        }
    }
    return NULL;
}

// 修改后的共享内存更新函数
void update_shared_memory(int key, const char *value) {
    if (shm_arr == NULL) {
        printf("共享内存未初始化\n");
        return;
    }
    
    pthread_mutex_lock(&shm_mutex);
    
    // 在整个设备数组中查找匹配的key
    for (int i = 0; i < *shm_total_devices; i++) {
        if (shm_arr[i].key == key && shm_arr[i].dev_type == DEV_TYPE_STM32) {
            // 保存旧值
            shm_arr[i].old_val = shm_arr[i].new_val;
            
            // 根据数据类型更新新值
            switch (shm_arr[i].type) {
                case DATA_TYPE_BOOL: // BOOL (type=1)
                    shm_arr[i].new_val.b_val = (strcmp(value, "1") == 0) ? 1 : 0;
                    break;
                    
                case DATA_TYPE_INT: // INT (type=2)
                    shm_arr[i].new_val.i_val = atoi(value);
                    break;
                    
                case DATA_TYPE_FLOAT: // FLOAT (type=3)
                    shm_arr[i].new_val.f_val = atof(value);
                    break;
            }
            
            shm_arr[i].ret = 0; // 成功
            printf("更新共享内存: key=%d, value=%s (位置:%d)\n", key, value, i);
            break;
        }
    }
    
    pthread_mutex_unlock(&shm_mutex);
}

// 修改后的JSON数据处理函数
void process_json_data(char *json_str) {
    cJSON *root = cJSON_Parse(json_str);
    if (!root) {
        printf("JSON解析失败: %s\n", json_str);
        return;
    }
    
    // 解析设备数据
    cJSON *data_obj = cJSON_GetObjectItem(root, "data");
    if (!data_obj) {
        printf("未找到data节点\n");
        cJSON_Delete(root);
        return;
    }
    
    // 遍历所有STM32设备
    for (int i = 0; i < stm32_device_count; i++) {
        if (i >= STM32_DEVICE_COUNT) break;
        
        // 使用设备名作为键查找值
        cJSON *value_obj = cJSON_GetObjectItem(data_obj, stm32_devices[i].name);
        if (!value_obj) {
            // 尝试使用key作为备选查找方式
            char key_str[16];
            snprintf(key_str, sizeof(key_str), "%d", stm32_devices[i].key);
            value_obj = cJSON_GetObjectItem(data_obj, key_str);
            
            if (!value_obj) {
                printf("未找到设备 %s (key=%d) 的数据\n", 
                      stm32_devices[i].name, stm32_devices[i].key);
                continue;
            }
        }
        
        char value_str[20] = {0};
        
        // 根据数据类型获取值 (不使用cJSON_Is*辅助函数)
        if (value_obj->type == cJSON_Number) {
            // 根据设备类型处理值
            if (stm32_devices[i].type == DATA_TYPE_FLOAT) { // FLOAT (type=3)
                snprintf(value_str, sizeof(value_str), "%.2f", value_obj->valuedouble);
            } else { // BOOL or INT
                snprintf(value_str, sizeof(value_str), "%d", (int)value_obj->valuedouble);
            }
        } 
        else if (value_obj->type == cJSON_String) {
            strncpy(value_str, value_obj->valuestring, sizeof(value_str) - 1);
        }
        else if (value_obj->type == cJSON_True) {
            strcpy(value_str, "1");
        }
        else if (value_obj->type == cJSON_False) {
            strcpy(value_str, "0");
        }
        else {
            printf("设备 %s 的值类型无效 (类型:%d)\n", stm32_devices[i].name, value_obj->type);
            continue;
        }
        
        // 更新共享内存
        update_shared_memory(stm32_devices[i].key, value_str);
    }
    
    cJSON_Delete(root);
}

void handler(int sig) {
    while (waitpid(-1, NULL, WNOHANG) > 0);
}

int main(int argc, char const *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <port>\n", argv[0]);
        return -1;
    }
    
    // 1. 解析配置文件
    if (parse_config("./node.json") < 0) {
        return -1;
    }
    
    // 2. 初始化共享内存
    if (init_shared_memory() != 0) {
        printf("共享内存初始化失败\n");
        return -1;
    }
    
    // 3. 创建处理控制信息的子线程
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler_thread, NULL) != 0) {
        perror("创建控制线程失败");
        return -1;
    }
    pthread_detach(tid);
    
    // 4. 创建TCP套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket err");
        return -1;
    }
    
    // 设置SO_REUSEADDR选项
    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
        perror("setsockopt(SO_REUSEADDR) failed");
        close(sockfd);
        return -1;
    }
    
    printf("socket fd: %d\n", sockfd);
    
    // 5. 绑定套接字
    struct sockaddr_in saddr, caddr;
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(atoi(argv[1]));
    saddr.sin_addr.s_addr = INADDR_ANY;
    socklen_t len = sizeof(caddr);
    
    if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
        perror("bind err");
        close(sockfd);
        return -1;
    }
    printf("bind ok\n");
    
    // 6. 监听套接字
    if (listen(sockfd, 6) < 0) {
        perror("listen err");
        close(sockfd);
        return -1;
    }
    printf("listen ok\n");
    
    signal(SIGCHLD, handler);
    
    // 7. 接受客户端连接
    while (1) {
        int acceptfd = accept(sockfd, (struct sockaddr *)&caddr, &len);
        if (acceptfd < 0) {
            perror("accept err");
            continue;
        }
        
        printf("accept fd: %d\n", acceptfd);
        printf("client port: %d, ip: %s\n", ntohs(caddr.sin_port), inet_ntoa(caddr.sin_addr));
        
        pid_t pid = fork();
        if (pid < 0) {
            perror("fork err");
            close(acceptfd);
            continue;
        } else if (pid == 0) {
            // 子进程处理客户端连接
            close(sockfd);
            
            char buf[1024] = {0};
            while (1) {
                int ret = recv(acceptfd, buf, sizeof(buf) - 1, 0);
                if (ret < 0) {
                    perror("recv err");
                    break;
                } else if (ret == 0) {
                    printf("client disconnected\n");
                    break;
                } else {
                    buf[ret] = '\0';
                    printf("Received JSON: %s\n", buf);
                    
                    // 处理JSON数据
                    process_json_data(buf);
                    
                    // 清空缓冲区
                    memset(buf, 0, sizeof(buf));
                }
            }
            
            close(acceptfd);
            exit(0);
        } else {
            // 父进程继续监听新连接
            close(acceptfd);
        }
    }
    
    close(sockfd);
    
    // 清理资源
    if (stm32_devices) {
        free(stm32_devices);
    }
    
    return 0;
}